package myself.study.network.tcp.examples;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
* @Name: TcpServer
* @Description: tcp协议数据传输服务端
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-1-12 下午1:05:42 
* @Version: V1.0
 */
public class TcpServer {
	
	public static void main(String[] args) throws IOException {
		//创建服务端Socket对象
		ServerSocket server = new ServerSocket(12345) ;
		System.out.println("启动tcp服务器...");
		//声明数据输入输出流对象
		DataInputStream dataInputStream = null ;
		DataOutputStream dataOutputStream = null ;
		while(true) {
			try {
				//监听客户端连接，获取客户端Socket对象
				Socket socket = server.accept() ;
				//获取输入流对象
				dataInputStream = new DataInputStream(socket.getInputStream()) ;
				//接收客户端发送的请求数据
				String requestData = dataInputStream.readUTF() ;
				//获取客户端ip地址
				String hostAddress = socket.getInetAddress().getHostAddress() ;
				System.out.println("from client -> " + hostAddress + " : " + requestData);
				//处理客户端请求
				//休眠2秒 ... 模拟处理过程
				Thread.sleep(2000) ;
				//处理结果
				String responseData = "知道了，忙你的事吧！" ;
				//获取输出流对象
				dataOutputStream = new DataOutputStream(socket.getOutputStream()) ;
				//向客户端响应结果
				dataOutputStream.writeUTF(responseData) ;
				System.out.println("to client -> " + hostAddress + " : " + responseData);
			} catch (Exception e) {
				e.printStackTrace() ;
			} finally {
				//释放资源
				if(dataInputStream != null) {
					try {
						dataInputStream.close() ;
					} catch (Exception e2) {
						e2.printStackTrace() ;
					} finally {
						dataInputStream = null ;
					}
				}
				if(dataOutputStream != null) {
					try {
						dataOutputStream.close() ;
					} catch (Exception e2) {
						e2.printStackTrace() ;
					} finally {
						dataOutputStream = null ;
					}
				}
			}
		}
 	}

}
